﻿using System;
using System.Text.RegularExpressions;
using Elca.MvvmHelpers;

namespace ULSDeobfuscator {

    /// <summary>
    /// Used to filter text messages
    /// </summary>
    public class ComplexFilter : BaseNotifyableObject {
        private string _filterExpression;
        public string FilterExpression {
            get { return _filterExpression; }
            set {
                _filterExpression = value;
                OnPropertyChanged("FilterExpression");
            }
        }

        private bool _isRegex;
        public bool IsRegex {
            get { return _isRegex; }
            set {
                _isRegex = value;
                OnPropertyChanged("IsRegex");
            }
        }

        private bool _isCaseSensitive;
        public bool IsCaseSensitive {
            get { return _isCaseSensitive; }
            set {
                _isCaseSensitive = value;
                OnPropertyChanged("IsCaseSensitive");
            }
        }

        private Regex _regex;
        private string _lowerExpression;

        public void CopyTo(ComplexFilter destination) {

            destination.FilterExpression = FilterExpression;
            destination.IsCaseSensitive = IsCaseSensitive;
            destination.IsRegex = IsRegex;
        }

        public ComplexFilter Clone() {
            
            ComplexFilter newCF = new ComplexFilter();
            CopyTo(newCF);

            return newCF;
        }

        public void SetupComparison() {
        
            if (_isRegex) {
                
                _regex = new Regex(_filterExpression, _isCaseSensitive ? RegexOptions.Compiled : (RegexOptions.Compiled | RegexOptions.IgnoreCase));
            } else {
                
                if (! _isCaseSensitive) {
                    _lowerExpression = FilterExpression.ToLowerInvariant();
                }
            }
        }

        public bool IsMatch(LogEntry le) {
            
            if (_isRegex) {
                if (_isCaseSensitive) {
                    return _regex.IsMatch(le.Message);
                }

                return _regex.IsMatch(le.LowerCaseMessage);
            }

            if (_isCaseSensitive) {
                return le.Message.Contains(FilterExpression);
            }

            return le.LowerCaseMessage.Contains(_lowerExpression);
        }
    }
}
